import { login, logout, getInfo } from "@/api/user";
import {staticRoutes,allAsyncRoutes,anyRoute} from '@/router/routes'
import router from '@/router'
import cloneDeep from 'lodash/cloneDeep'
router.options.routes = staticRoutes
function filterAsyncRoutes(allAsyncRoutes,routeNames){
  return allAsyncRoutes.filter(item => {
    if(routeNames.indexOf(item.name) !== -1){
      if(item.children && item.children.length >0){
        item.children = filterAsyncRoutes( item.children,routeNames)
      }
      return true
    }
  })
}
function addRoutes(routes){
  router.addRoute(routes) 
}
function resetRoutes(staticRoutes){
  let routes = router.getRoutes() //获取路由器当中的所有路由组成的数组
  routes.forEach(item =>{
    if(item.name){
      router.removeRoute(item.name)
    }
  })
  addRoutes(staticRoutes)
}

const state = {
  token: localStorage.getItem("token_key") || "",
  // routes: [],
  userInfo:{},
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_INFO(state, userInfo) {
    state.userInfo = userInfo;
  },
  SET_ROMETOKEN(state) {
    state.token = ""
  },
  RESET_USERINFO(state,){
    state.userInfo = {}
    state.token = ""
  }
};
const actions = {
  // 登录
  async login({ commit }, loginParams) {
    try {
      const result = await login(loginParams);
      commit("SET_TOKEN", result.data.token);
      this.getUserInfo
      localStorage.setItem("token_key", result.data.token);
      return "ok";
    } catch (error) {
      return Promise.reject(new Error("获取失败"));
    }
  },

  // 获取用户信息
  async getUserInfo({ commit }) {
    
    try {
      const result = await getInfo();
      commit("SET_INFO", result.data);
      console.log('xxxxx',result.data);
      let userAsyncRoutes = filterAsyncRoutes(cloneDeep(allAsyncRoutes),result.data.routes)
      userAsyncRoutes.push(addRoutes)
      router.addRoutes(userAsyncRoutes)
      router.options.routes = staticRoutes.concat(userAsyncRoutes)
      return "ok";
    } catch (error) {
      return Promise.reject(new Error("获取用户信息失败"));
    }
  },

  //清楚token
  resetToken({ commit }) {
    localStorage.removeItem("token_key");
    commit("SET_ROMETOKEN");
  },
  //退出登录
  async logout({ commit, dispatch }) {
    try {
      const result = await logout();
      if (result.code === 20000) {
        //清空token
        dispatch("resetToken");
        //清空用户信息
        commit("RESET_USERINFO");
        // resetRoutes(staticRoutes)

        return "ok";
      } else {
        return Promise.reject(new Error("failed"));
      }
    } catch (error) {
      return Promise.reject(new Error("失败"));
    }
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
